package com.example.musictutor.services;

import android.content.Context;
import android.util.Log;
import android.widget.ImageButton;

import com.example.musictutor.R;
import com.example.musictutor.activities.PlaySongActivity;
import com.example.musictutor.domain.Song;
import com.example.musictutor.services.listeners.PlaySongCompletionListener;
import com.example.musictutor.services.playfunctionobserver.PlayFunctionsInterface;
import com.example.musictutor.services.runnables.PlayRunnable;

public class PlaySong implements PlayFunctionsInterface {

	public static final int IDLE = 0;
	public static final int ACTIVE = 1;

	private int state;
	private PlayRunnable playRunnable;
	private Context context;
	private Song songPlaying;
	
	private PlaySongCompletionListener completionListener = new PlaySongCompletionListener() {
		
		PlaySongActivity activity = null;
		
		@Override
		public void playSongCompleted() {
			state = IDLE;
			activity = (PlaySongActivity) context;
			
			activity.runOnUiThread(new Runnable() {
				public void run() {
					KeyBoard.getInstance().setEnabled(true);
					ImageButton playSongButton = (ImageButton) activity.findViewById(R.id.playSongButton);
					playSongButton.setImageResource(R.drawable.play_image);
					activity.songFinished();	
				}
			});
		}
	};

	public PlaySong(Song song, Context context) {
		state = IDLE;
		this.context = context;
		this.songPlaying = song;
		playRunnable = new PlayRunnable(song, context);
		playRunnable.setPlaysongCompletionListener(completionListener);
	}

	public int getState() {
		return state;
	}

	public void setState(int state) {
		this.state = state;
	}

	public Song getSong() {
		return songPlaying;
	}
	
	@Override
	public void playPressed() {
		
		if(state == IDLE) {
			state = ACTIVE;
			KeyBoard.getInstance().setEnabled(false);
			Thread thread = new Thread(playRunnable);
			thread.start();
		}
		else if(state == ACTIVE) {
			KeyBoard.getInstance().setEnabled(false);
			playRunnable.playPressed();
		}
	}

	@Override
	public void pausePressed() {
		Log.d("Observer", "PlaySong - pausePressed");
		if(state == ACTIVE) {
			playRunnable.pausePressed();
			KeyBoard.getInstance().setEnabled(true);
		}
	}

	@Override
	public void restartPressed() {
		if(state == ACTIVE)
			playRunnable.restartPressed();
	}
}
